package com.jooink.sharewidget.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class ShareWidgetPlus implements IsWidget{

	private static boolean plus_initialized=false;
	private static boolean plus_failed=false;

	static {
		//G-plus script injection
		ScriptInjector.fromUrl("https://apis.google.com/js/plusone.js").setCallback(
				new Callback<Void, Exception>() {
					@Override
					public void onSuccess(Void result) {
						plus_initialized=true;
						vis_plus_element();
					}
					@Override
					public void onFailure(Exception reason) {
						plus_failed=true;
					}
				}
				).setWindow(ScriptInjector.TOP_WINDOW).inject();		

	}
	//G-plus static list
	static List<Element> gplus_list=new ArrayList<Element>();
	static List<PlusOptions> gplus_opts=new ArrayList<PlusOptions>();

	//G-plus repeating command
	static void vis_plus_element() {
		for(int i=0;i<gplus_list.size();i++) {
			plus_render(gplus_list.get(i),gplus_opts.get(i));
		}
		gplus_list.clear();
		gplus_opts.clear();
	};


	//Plus Button
	public ShareWidgetPlus(String href, String size, String annotation) {
		final PlusOptions po=createOptions(href, size, annotation);
		plus.addAttachHandler(new AttachEvent.Handler() {
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if(event.isAttached()) {
					render_plus(po);
				}
			}
		});
	}

	private void render_plus(PlusOptions po) {
		if(plus_failed)
			return;
		if(plus_initialized) {
			plus_render(plus.getElement(),po);
		} else {
			gplus_list.add(plus.getElement());
			gplus_opts.add(po);
		}
	}
	
	public static class PlusOptions extends JavaScriptObject {
		protected PlusOptions() {};
	}
	
	public native static PlusOptions createOptions(String href, String size, String annotation) /*-{
		return {href:href,size:size,annotation:annotation};
	}-*/;

	private static native void plus_render(Element e, PlusOptions po) /*-{
		$wnd.gapi.plusone.render(e,po);
	}-*/;

	private HTML plus=new HTML();

	@Override
	public Widget asWidget() {
		return plus;
	}


}
